package com.gthncz.xxhelper.adapters;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gthncz.xxhelper.R;
import com.gthncz.xxhelper.greendao.Subject;

import java.util.List;

/**
 * 搜索结果适配器
 * Created by GT on 2019/11/11.
 */

public class SubjectRecycleAdapter extends RecyclerView.Adapter {

    private List<Subject> data;
    private Context context;

    public SubjectRecycleAdapter(Context context, List<Subject> data){
        this.context = context;
        this.data = data;
    }

    public void setData(List<Subject> data) {
        if (data != this.data){ // 比较地址
            Log.e("Adapter","data addr not equal.");
            this.data.clear(); //  会指向新内存地址?
            for(Subject subject: data){
                this.data.add(subject);
            }
        } else Log.e("Adapter","data addr equal.");
        Log.e("Adapter", "data size:" + this.data.size());
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View root = inflater.inflate(R.layout.layout_item, null);
        return new SubjectViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final Subject subject = data.get(position);
        final SubjectViewHolder mHolder = (SubjectViewHolder) holder;
        mHolder.setSubject(subject);
        mHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 处理点击事件
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class SubjectViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_question;
        private TextView tv_answer;

        public SubjectViewHolder(View itemView) {
            super(itemView);
            tv_question = itemView.findViewById(R.id.textView_item_question);
            tv_answer = itemView.findViewById(R.id.textView_item_answer);
        }

        public void setSubject(Subject subject){
            tv_answer.setText(subject.getAnswer());
            tv_question.setText(subject.getQuestion());
        }
    }
}
